package com.example.jasonparserdemo;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonParserActivity extends AppCompatActivity {

    private String JSON_STR = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        JSON_STR = getResources().getString(R.string.Json);
        Button btn = (Button) findViewById(R.id.bnt);
        btn.setText("解析Json");
        final ListView list = (ListView) findViewById(R.id.list);
        btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                List<Map<String, Object>> data = parseJson(JSON_STR);
                SimpleAdapter sa = new SimpleAdapter(JsonParserActivity.this,
                        data, R.layout.book_line, new String[]{"name",
                        "date", "price"}, new int[]{R.id.name,
                        R.id.date, R.id.price});
                list.setAdapter(sa);
            }
        });
    }

    public List<Map<String, Object>> parseJson(String str) {
        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

        JSONObject jo;
        try {
            jo = new JSONObject(str);
            JSONArray ja = new JSONArray(jo.getString("books"));
            for (int i = 0; i < ja.length(); i++) {
                JSONObject book = ja.getJSONObject(i);
                Map<String, Object> item = new HashMap<String, Object>();
                item.put("price", book.getString("price"));
                item.put("date", book.getString("出版日期"));
                item.put("name", book.getString("name"));
                result.add(item);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return result;
    }
}
